package lacus.wd_cinema.service;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lacus.wd_cinema.dto.auth.LoginRequest;
import lacus.wd_cinema.dto.auth.RegisterRequest;
import lacus.wd_cinema.entity.User;
import lacus.wd_cinema.exception.ValidationException;
import lacus.wd_cinema.exception.UnauthorizedException;
import lacus.wd_cinema.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

/**
 * 用户认证业务处理类
 *
 * @author lacus
 * @version 0.5
 * @since 0.5
 */
@Service
@Transactional
public class AuthService {
    private final UserRepository userRepository;

    public AuthService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /** 用户登录 */
    public void login(
            LoginRequest loginRequest,
            HttpServletRequest servletRequest) {
        User user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(
                () -> new ValidationException("用户名或密码不正确"));
        if (user.getPassword().equals(loginRequest.getPassword())) {
            HttpSession session = servletRequest.getSession();
            session.setAttribute("user", user);
        } else throw new ValidationException("用户名或密码不正确");
    }

    /** 用户登出 */
    public void logout(HttpServletRequest servletRequest) {
        HttpSession session = servletRequest.getSession(false);
        if (session != null) session.invalidate();
    }

    /** 用户注册 */
    public void register(
            RegisterRequest registerRequest) {
        User user = new User();
        BeanUtils.copyProperties(registerRequest, user);
        user.setRole(User.Role.ROLE_USER);
        user.setCreatedAt(LocalDate.now());
        userRepository.save(user);
    }

    /** 获取当前登录的用户 */
    public User getCurrentUser(HttpServletRequest servletRequest) {
        HttpSession session = servletRequest.getSession(false);
        if (session == null) throw new UnauthorizedException("用户未认证");
        User user = (User) session.getAttribute("user");
        if (user == null) throw new UnauthorizedException("用户未认证");
        return user;
    }
}

